# -*- coding: utf-8 -*-
import sys
import os

def openTable():
    f = open('C:/Users/Hu/Downloads/chinese2pinyin/gb-pinyin.table', 'r')
    table = f.read()
    f.close()
    return table

def searchPinyin(num, table):
    if(num>0 & num<160):
        return chr(num)

    v=table.split(';')
    for i in xrange(len(v)-1,-1,-1):
        s=v[i].split(',')
        if int(s[1])<=num:
            return s[0]
            break

def convertPY(chinese):
    i=0
    str = ''
    while(i<len(chinese)):
        try:
            p = ord(chinese[i:i+1])
            if(p>160):
                i+=1
                q = ord(chinese[i:i+1])
                p = p*256+q-65536
                #print p, q
                str = '%s%s ' % (str, searchPinyin(p,table))
            else:
                str = '%s%s' % (str, searchPinyin(p,table))
        except:
            #str = '%s%s' % (str, chinese[i:i+1])
            return chinese
            #print chinese
        i+=1
        #str = '%s%s ' % (str, searchPinyin(p,table))

    print str
    return str
        
if __name__ == "__main__":
    table = openTable()


    #chinese = '李宗盛 - 理智与情感作品音乐会'
    #chinese = chinese.decode('utf8').encode('gbk')

    root_dir = 'c:/temp/temp1'
    #filelist = os.listdir(root_dir)
    for dirname, dirnames, filenames in os.walk(root_dir):
        #print files
        for filename in filenames:
            #print os.path.join(dirname, filename)
            #print filename[-4:]
            if filename[-4:] == '.mp3':
                opath = os.path.join(dirname, filename)
                nfilename = convertPY(filename[:-4]) + '.mp3'
                npath = os.path.join(dirname, nfilename)
                #print opath, npath
                os.rename(opath, npath)
            #print temp

    #data_files = [x[2] for x in os.walk(root_dir)]
    #print data_files[1]
    #for item in data_files[1]:
    #for item in filelist:
    #for i in range(len(filelist)):
        #print filelist[i]
        #temp = convertPY(item[:-4])
        #temp = convertPY(filelist[i])
        #os.rename(root_dir + '/' + filelist[i], root_dir + '/' + temp)
        

